package routers

import (
	"server/global"
	"server/internal/service"
	"server/pkg/app"
	"server/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type Course struct{}

func NewCourse() *Course {
	return &Course{}
}

func (cs *Course) NewCourse(c *gin.Context) {
	param := &struct {
		Name         string `form:"name" binding:"required"`
		Description  string `form:"description" binding:"required"`
		ChainName    string `form:"chainName" binding:"required"`
		ChainAccount string `form:"chainAccount" binding:"required"`
		Username     string `form:"username" binding:"required"`
		Start        int    `form:"start" binding:"required"`
		End          int    `form:"end" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	err := svc.NewCourse(param.Name, param.Description, param.ChainName,
		param.ChainAccount, param.Username, param.Start, param.End)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorNewCourseFail)
		return
	}

	response.ToSuccessResponse(nil)
}

func (cs *Course) GetMyCourses(c *gin.Context) {
	param := &struct {
		Username string `form:"username" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	courses, err := svc.GetMyCourses(param.Username)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorGetCourseFail)
		return
	}

	response.ToSuccessResponse(courses)
}

func (cs *Course) GetCurrentCourses(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c.Request.Context())
	courses, err := svc.GetCurrentCourses()
	if err != nil {
		response.ToErrorResponse(errcode.ErrorGetCourseFail)
		return
	}

	response.ToSuccessResponse(courses)
}

func (cs *Course) DeleteCourse(c *gin.Context) {
	param := &struct {
		ID int `form:"id" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	err := svc.DeleteCourse(param.ID)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorDeleteCourseFail)
		return
	}

	response.ToSuccessResponse(nil)
}
